import databases
import sqlalchemy
from .config import settings

# 使用 databases 库来提供异步连接池
database = databases.Database(settings.DATABASE_URL)

# 使用 SQLAlchemy Core 定义表结构 (元数据)
metadata = sqlalchemy.MetaData()

users = sqlalchemy.Table(
    "users",
    metadata,
    sqlalchemy.Column("id", sqlalchemy.Integer, primary_key=True),
    sqlalchemy.Column("name", sqlalchemy.String, nullable=False),
)

face_features = sqlalchemy.Table(
    "face_features",
    metadata,
    sqlalchemy.Column("feature_id", sqlalchemy.Integer, primary_key=True, autoincrement=True),
    sqlalchemy.Column("user_id", sqlalchemy.Integer, sqlalchemy.ForeignKey("users.id", ondelete="CASCADE"), nullable=False),
    sqlalchemy.Column("embedding", sqlalchemy.LargeBinary, nullable=False),
    sqlalchemy.Index("ix_face_features_user_id", "user_id"),
)

# 创建一个引擎，用于在启动时创建表
engine = sqlalchemy.create_engine(settings.DATABASE_URL.replace("+asyncpg", ""))

def create_tables():
    """创建所有定义的表"""
    metadata.create_all(engine)